package com.blb.controller;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.blb.entity.Menu;
import com.blb.entity.MenuExample;
import com.blb.entity.MenuExt;
import com.blb.mapper.MenuExtMapper;
import com.blb.mapper.MenuMapper;
import com.blb.utils.SessionUtils;
import com.blb.utils.UUIDUtils;

@Controller
@RequestMapping("menu")
public class MenuController {
	
	@Autowired
	private MenuExtMapper menuExtMapper;
	
	@Autowired
	private MenuMapper menuMapper;
	
	@RequestMapping("showList")
	public String showList(String menuId, Model model) throws IOException{
		//查询当前用户拥有哪些按钮
		List<Menu> list = menuExtMapper.getButtonByUserId(SessionUtils.getUserId(), menuId);
		model.addAttribute("bts", list);
		return "menu/menu_list";
	}

	/**
	 * 列表
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("page")
	public List<Menu> page() throws IOException{
		MenuExample menuExample = new MenuExample();
		menuExample.setOrderByClause("seq");
		
		List<Menu> list = menuMapper.selectByExample(menuExample);
		return list;
	}
	
	/**
	 * 添加
	 * @param menu
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("save")
	public String save(Menu menu) throws IOException{
		menu.setId(UUIDUtils.getID());
		menu.setCreateTime(new Date());
		menu.setCreateUser(SessionUtils.getUserName());
		menuMapper.insert(menu);
		return "";
	}
	
	/**
	 * 获取父级菜单
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("getParentMenu")
	public List<MenuExt> getParentMenu() throws IOException{
		List<MenuExt> menuExts = menuExtMapper.getParentMenu();
		return menuExts;
	}
	
	/**
	 * 删除
	 * @param id
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("delete")
	public String delete(String id) throws IOException{
		MenuExample menuExample = new MenuExample();
		menuExample.createCriteria().andPidEqualTo(id);
		List<Menu> list = menuMapper.selectByExample(menuExample);
		if (!list.isEmpty()) {
			return "该节点下还有子节点，不允许删除";
		}
		menuMapper.deleteByPrimaryKey(id);
		return "";
	}
	
	@ResponseBody
	@RequestMapping("update")
	public String update(Menu menu) throws IOException{
		menu.setUpdateUser(SessionUtils.getUserName());
		
		menuMapper.updateByPrimaryKeySelective(menu);
		return "";
	}
}
